﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data.Entity;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Description;
using ActiveDirectory.Models;

namespace ActiveDirectory.Controllers
{
    [Authorize]
    public class AdController : ApiController
    {
        private AdContext adContext = new AdContext();

        [ResponseType(typeof(AdAdmin))]
        public async Task<IHttpActionResult> Get()
        {
            var userId = User.Identity.Name;

            var admin = await NextAdmin();

            if (admin == null)
            {
                return this.NotFound();
            }

            return this.Ok(admin);
        }

        private async Task<AdAdmin> NextAdmin()
        {
            return await adContext.AdAdmins.FirstOrDefaultAsync();
            //var lastQuestionId = await this.db.TriviaAnswers
            //    .Where(a => a.UserId == userId)
            //    .GroupBy(a => a.QuestionId)
            //    .Select(g => new { QuestionId = g.Key, Count = g.Count() })
            //    .OrderByDescending(q => new { q.Count, QuestionId = q.QuestionId })
            //    .Select(q => q.QuestionId)
            //    .FirstOrDefaultAsync();

            //var questionsCount = await this.db.TriviaQuestions.CountAsync();

            //var nextQuestionId = (lastQuestionId % questionsCount) + 1;
            //return await this.db.TriviaQuestions.FindAsync(CancellationToken.None, nextQuestionId);
        }


        //[ResponseType(typeof(AdUser))]
        //public async Task<IHttpActionResult> GetUser()
        //{
        //    var users = await adContext.AdUsers.ToListAsync();

        //    if (users == null)
        //    {
        //        return this.NotFound();
        //    }

        //    return this.Ok(users);
        //}

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.adContext.Dispose();
            }

            base.Dispose(disposing);
        }
    }
}
